package 深入反射机制.反射属性Field.访问对象属性.test01;

import java.lang.reflect.Field;
import java.util.ResourceBundle;

//通过反射机制访问对象属性
public class ReflectTest01 {
    public static void main(String[] args) {
        ResourceBundle bundle = ResourceBundle.getBundle("invincibleConfiguration");
        String path = bundle.getString("studentClass");
        String jojo = bundle.getString("jojo");
        String age = bundle.getString("age");
        String name = bundle.getString("name");
        Object obj = null;
        Class studentClass = null;
        Field jojoField = null;
        Field ageField = null;
        try {
            studentClass = Class.forName(path);
            obj = studentClass.newInstance();

            //获取属性Field
            jojoField = studentClass.getDeclaredField(jojo);
            ageField = studentClass.getDeclaredField(age);
            Field nameField = studentClass.getDeclaredField(name);

            //修改
            ageField.set(obj,33);

            //打破封装
            nameField.setAccessible(true);
            nameField.set(obj,"神父");
            
            //得到
            System.out.println(ageField.get(obj));
            System.out.println(jojoField.get(obj));
            System.out.println(nameField.get(obj));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

    }
}













